package related

import (
	"fmt"

	"github.com/jinzhu/gorm"
)

// type User1 struct {
// 	Id   int
// 	Name string
// 	Age  int
// 	Addr string
// }

// type GradeInfo struct {
// 	Grade int
// 	Class int
// 	User  User1 `form:"ForeignKey:UId;AssociationForeignkey:Id"`
// 	UId   int
// }

type User2 struct {
	Id         int
	Name       string
	Age        int
	Addr       string
	GradeInfo2 []GradeInfo2 `gorm:"ForeignKey:UId;AssociationForeignkey:Id"`
}

type GradeInfo2 struct {
	Id    int
	Grade int
	Class int
	UId   int
}

func CreateOneToMany(db *gorm.DB) {
	db.AutoMigrate(&User2{}, &GradeInfo2{})
	//创建one_to_one
	user2 := User2{
		Name: "xiaosan",
		Age:  11,
		Addr: "湖北",
		GradeInfo2: []GradeInfo2{
			{Grade: 2, Class: 3},
			{Grade: 5, Class: 6},
			{Grade: 7, Class: 8},
		},
	}

	db.Create(&user2)
}

func QueryOneToMany(db *gorm.DB) {
	//创建one_to_Many
	//第一种查询方式
	var user2 User2

	db.Preload("GradeInfo2").Find(&user2, 1)
	fmt.Println(user2)

	//第二种查询方式
	var user3 User2
	db.First(&user3, 1)

	db.Model(&user3).Association("GradeInfo2").Find(&user3.GradeInfo2)

	fmt.Println(user3)

	//第三种查询方式
	var user4 User2
	db.First(&user4, 1)
	var grade3 []GradeInfo2
	db.Model(&user4).Related(&grade3, "GradeInfo2")

	fmt.Println(user4)
	fmt.Println(grade3)
}

func UpdateOneToMany(db *gorm.DB) {
	//创建one_to_one
	var user User2
	db.Preload("GradeInfo2").Find(&user, 1)

	db.Model(&user.GradeInfo2).Where("Id = ?", 2).Update("Grade", 6)
	fmt.Println(user)
}

func DelOneToMany(db *gorm.DB) {
	//创建one_to_one
	var user User2
	db.Preload("GradeInfo2").Find(&user, 1)
	db.Where("Id=?", 2).Delete(&user.GradeInfo2)
	fmt.Println(user)
}
